<template>
  <div>
    <div class="header-content">
      <div>
        <h1 style="color: #0d0e10;">咨询系统数据统计</h1>
      </div>
      <div class="filters">
        <div class="filter-group">
          <p>时间范围：</p>
          <select v-model="selectedTimeRange">
            <option value="week">最近一周</option>
            <option value="month">最近一月</option>
            <option value="term">本学期</option>
            <option value="year">本学年</option>
          </select>
        </div>
        <div class="filter-group">
          <p>学院：</p>
          <select v-model="selectedCollege">
            <option value="all">全部学院</option>
            <option value="computer">计算机学院</option>
            <option value="wine">白酒学院</option>
            <option value="money">商学院</option>
            <option value="english">外国语学院</option>
            <option value="article">文传学院</option>
            <option value="art">艺术学院</option>
            <option value="sport">体育学院</option>
          </select>
        </div>
        <div class="filter-group">
          <p>年级：</p>
          <select v-model="selectedGrade">
            <option value="all">全部年级</option>
            <option value="freshman">大一</option>
            <option value="sophomore">大二</option>
            <option value="junior">大三</option>
            <option value="senior">大四</option>
            <option value="graduate">研究生</option>
          </select>
        </div>
      </div>
    </div>

    <div class="charts-grid">
      <div class="chart-container">
        <h2>咨询问题类别分布</h2>
        <div class="chart-wrapper" ref="rose"></div>
      </div>
      <div class="chart-container">
        <h2>月度咨询量趋势</h2>
        <div class="chart-wrapper" ref="line"></div>
      </div>
      <div class="chart-container">
        <h2>风险等级分布</h2>
        <div class="chart-wrapper" ref="gauge"></div>
      </div>
      <div class="chart-container">
        <h2>咨询师工作量对比</h2>
        <div class="chart-wrapper" ref="bar"></div>
      </div>
      <div class="chart-container">
        <h2>咨询时段分布</h2>
        <div class="chart-wrapper" ref="heatmap"></div>
      </div>
      <div class="chart-container">
        <h2>预约男女比例分布</h2>
        <div class="chart-wrapper" ref="genderRatio"></div>
      </div>
    </div>

    <footer>
      <p>
        © 2025 四川大学锦江学院心理健康中心 | 数据更新时间: {{ currentTime }}
      </p>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

// 筛选器状态
const selectedTimeRange = ref('month');
const selectedCollege = ref('all');
const selectedGrade = ref('all');

// 图表引用
const rose = ref(null);
const line = ref(null);
const gauge = ref(null);
const bar = ref(null);
const heatmap = ref(null);
const genderRatio = ref(null);

// 图表实例
let RChart = null;
let LChart = null;
let GChart = null;
let BChart = null;
let HTChart = null;
let GenderRatioChart = null;

const currentTime = ref('');

// 数据状态
const stats = ref({
  consultCount: 1248,
  warningCount: 87,
  counselorCount: 24,
  satisfaction: 92
});

const pathSymbols = {
  man: 'path://M-6 13 A1 1 0 0 0 -4 13 A1 1 0 0 0 -6 13',
  woman: 'path://M-6 13 A1 1 0 0 0 -4 13 A1 1 0 0 0 -6 13'
};

// 标签设置
const labelSetting = {
  show: true,
  position: 'right',
  offset: [10, 0],
  fontSize: 14
};

// 更新时间
const updateDateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 创建性别比例图表选项
const createGenderRatioOption = () => {
  return {
    tooltip: {
      trigger: 'axis',
    },
    yAxis: {
      data: ['男', '女'],
      inverse: true,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        margin: 30,
        fontSize: 14
      }
    },
    xAxis: {
      splitLine: { show: false },
      axisTick: { show: false },
      axisLine: { show: false }
    },
    series: [
      {
        type: 'pictorialBar',
        label: labelSetting,
        symbolRepeat: true,
        symbolSize: ['60%', '60%'],
        barCategoryGap: '60%',
        data: [
          {
            value: 157,
            symbol: pathSymbols.man,
            itemStyle: { color: '#00BFFF' } // 男性蓝色
          },
          {
            value: 66,
            symbol: pathSymbols.woman,
            itemStyle: { color: '#FFB6C1' } // 女性粉色
          }
        ]
      },
    ]
  };
};

// 仪表盘数据
const gaugeData = ref([
  {
    value: 20,
    name: '低风险',
    title: {
      offsetCenter: ['-40%', '80%']
    },
    detail: {
      offsetCenter: ['-40%', '95%']
    }
  },
  {
    value: 40,
    name: '中风险',
    title: {
      offsetCenter: ['0%', '80%']
    },
    detail: {
      offsetCenter: ['0%', '95%']
    }
  },
  {
    value: 60,
    name: '高风险',
    title: {
      offsetCenter: ['40%', '80%']
    },
    detail: {
      offsetCenter: ['40%', '95%']
    }
  }
]);

// 初始化图表
const initCharts = () => {
  // 玫瑰图 - 咨询问题类别分布
  if (rose.value) {
    RChart = echarts.init(rose.value);
    RChart.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['学业压力', '情感问题', '人际关系', '家庭问题', '适应问题', '其他']
      },
      series: [{
        name: '咨询问题类别',
        type: 'pie',
        radius: ['30%', '70%'],
        roseType: 'radius',
        itemStyle: { borderRadius: 8 },
        data: [
          { value: 3577, name: '学业压力' },
          { value: 2453, name: '情感问题' },
          { value: 2255, name: '人际关系' },
          { value: 1541, name: '家庭问题' },
          { value: 1025, name: '适应问题' },
          { value: 516, name: '其他' }
        ]
      }]
    });
  }

  // 折线图 - 月度咨询量趋势
  if (line.value) {
    LChart = echarts.init(line.value);
    LChart.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['咨询总量', '高危个案', '线上咨询'] },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['9月', '10月', '11月', '12月', '1月', '2月', '3月']
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '咨询总量',
          type: 'line',
          smooth: true,
          lineStyle: { width: 4 },
          data: [820, 932, 901, 934, 890, 730, 1248]
        },
        {
          name: '高危个案',
          type: 'line',
          smooth: true,
          lineStyle: { width: 3, type: 'dashed' },
          data: [120, 132, 101, 134, 90, 70, 87]
        },
        {
          name: '线上咨询',
          type: 'line',
          smooth: true,
          data: [320, 432, 501, 534, 590, 530, 748]
        }
      ]
    });
  }

  //仪表盘 - 风险等级分布
  if (gauge.value) {
    GChart = echarts.init(gauge.value);
    GChart.setOption({
      series: [
        {
          type: 'gauge',
          radius: '80%',
          min: 0,
          max: 100,
          splitNumber: 10,
          startAngle: 225,
          endAngle: -45,
          anchor: {
            show: true,
            showAbove: true,
            size: 18,
            itemStyle: {
              color: '#FAC858'
            }
          },
          pointer: {
            icon: 'path://M2.9,0.7L2.9,0.7c1.4,0,2.6,1.2,2.6,2.6v115c0,1.4-1.2,2.6-2.6,2.6l0,0c-1.4,0-2.6-1.2-2.6-2.6V3.3C0.3,1.9,1.4,0.7,2.9,0.7z',
            width: 8,
            length: '80%',
            offsetCenter: [0, '8%'],
            itemStyle: {
              color: 'auto'
            }
          },
          progress: {
            show: true,
            overlap: false,
            roundCap: true,
          },
          axisLine: {
            roundCap: true,
          },
          data: gaugeData.value,
          title: {
            fontSize: 14,
          },
          detail: {
            width: 40,
            height: 14,
            fontSize: 14,
            color: '#fff',
            backgroundColor: 'inherit',
            borderRadius: 3,
            formatter: '{value}%',
          }
        }
      ]
    });
  }

  // 柱状图 - 咨询师工作量对比
  if (bar.value) {
    BChart = echarts.init(bar.value);
    BChart.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: ['咨询次数', '平均评分'] },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'value' },
      yAxis: {
        type: 'category',
        data: ['王老师', '张老师', '李老师', '赵老师', '刘老师', '陈老师', '周老师']
      },
      series: [
        {
          name: '咨询次数',
          type: 'bar',
          label: { show: true, position: 'right' },
          data: [78, 65, 89, 93, 55, 76, 82]
        },
        {
          name: '平均评分',
          type: 'bar',
          label: { show: true, position: 'right', formatter: '{c}分' },
          data: [4.8, 4.6, 4.9, 4.7, 4.5, 4.8, 4.7]
        }
      ]
    });
  }

  // 热力图 - 咨询时段分布
  if (heatmap.value) {
    const hours = ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'];
    const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

    const data = [];
    for (let i = 0; i < days.length; i++) {
      for (let j = 0; j < hours.length; j++) {
        let value;
        if (i < 5) {
          value = Math.round(Math.random() * 8 + (j > 3 && j < 8 ? 12 : 0));
        } else {
          value = Math.round(Math.random() * 6 + (j > 6 && j < 10 ? 14 : 6));
        }
        data.push([j, i, value]);
      }
    }

    HTChart = echarts.init(heatmap.value);
    HTChart.setOption({
      tooltip: {
        position: 'top',
        formatter: (params) => `${days[params.value[1]]} ${hours[params.value[0]]}<br>咨询量: ${params.value[2]}`
      },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', data: hours, splitArea: { show: true } },
      yAxis: { type: 'category', data: days, splitArea: { show: true } },
      visualMap: {
        min: 0,
        max: 20,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: '10%',
        top: '5%',
      },
      series: [{
        name: '咨询量',
        type: 'heatmap',
        data: data,
        label: { show: true }
      }]
    });
  }

  // 性别比例图表
  if (genderRatio.value) {
    GenderRatioChart = echarts.init(genderRatio.value);
    GenderRatioChart.setOption(createGenderRatioOption());
  }
};

const updateCharts = () => {
  const timeFactor = selectedTimeRange.value === 'week' ? 0.3 :
      selectedTimeRange.value === 'month' ? 1 :
          selectedTimeRange.value === 'term' ? 2.5 : 4;
  const collegeFactor = selectedCollege.value === 'all' ? 1 : 0.5;

  // 更新仪表盘数据（确保总值不超过100%）
  const lowRisk = +(Math.random() * 40 * timeFactor * collegeFactor).toFixed(1);
  const midRisk = +(Math.random() * 30 * timeFactor * collegeFactor).toFixed(1);
  const highRisk = +(Math.random() * 30 * timeFactor * collegeFactor).toFixed(1);

  const total = lowRisk + midRisk + highRisk;
  const scaleFactor = total > 100 ? 100 / total : 1;

  gaugeData.value = [
    {
      value: lowRisk * scaleFactor,
      name: '低风险',
      title: { offsetCenter: ['-45%', '85%'] },
      detail: { offsetCenter: ['-45%', '100%'] }
    },
    {
      value: midRisk * scaleFactor,
      name: '中风险',
      title: { offsetCenter: ['0%', '85%'] },
      detail: { offsetCenter: ['0%', '100%'] }
    },
    {
      value: highRisk * scaleFactor,
      name: '高风险',
      title: { offsetCenter: ['45%', '85%'] },
      detail: { offsetCenter: ['45%', '100%'] }
    }
  ];

  // 更新统计数据
  stats.value = {
    consultCount: Math.round(1200 * timeFactor * collegeFactor).toLocaleString(),
    warningCount: Math.round(80 * timeFactor * collegeFactor),
    counselorCount: selectedCollege.value === 'all' ? 24 : 8,
    satisfaction: 90 + Math.floor(Math.random() * 6)
  };

  // 更新各图表数据
  if (RChart) RChart.setOption({ series: [{ data: [
        { value: Math.round(320 * timeFactor * collegeFactor), name: '学业压力' },
        { value: Math.round(240 * timeFactor * collegeFactor), name: '情感问题' },
        { value: Math.round(180 * timeFactor * collegeFactor), name: '人际关系' },
        { value: Math.round(150 * timeFactor * collegeFactor), name: '家庭问题' },
        { value: Math.round(100 * timeFactor * collegeFactor), name: '适应问题' },
        { value: Math.round(70 * timeFactor * collegeFactor), name: '其他' }
      ]}]});

  if (LChart) LChart.setOption({
    series: [
      { data: [820, 932, 901, 934, 890, 730, 1248].map(v => Math.round(v * timeFactor * collegeFactor)) },
      { data: [120, 132, 101, 134, 90, 70, 87].map(v => Math.round(v * timeFactor * collegeFactor)) },
      { data: [320, 432, 501, 534, 590, 530, 748].map(v => Math.round(v * timeFactor * collegeFactor)) }
    ]
  });

  // 更新仪表盘
  if (GChart) {
    GChart.setOption({
      series: [{
        data: gaugeData.value,
        axisLine: {
          lineStyle: {
            color: [
              [0.3, '#67e0e3'],
              [0.6, '#eae77c'],
              [1, '#fd666d']
            ]
          }
        }
      }]
    });
  }

  if (BChart) BChart.setOption({
    series: [
      { data: [78, 65, 89, 93, 55, 76, 82].map(v => Math.round(v * timeFactor * collegeFactor)) },
      { data: [4.8, 4.6, 4.9, 4.7, 4.5, 4.8, 4.7].map(v => v - (Math.random() * 0.2)) }
    ]
  });

  if (HTChart) {
    const data = [];
    for (let i = 0; i < 7; i++) {
      for (let j = 0; j < 12; j++) {
        let value = i < 5
            ? Math.round(Math.random() * 8 + (j > 3 && j < 8 ? 10 : 0) * timeFactor * collegeFactor)
            : Math.round(Math.random() * 4 + (j > 6 && j < 10 ? 20 : 15) * timeFactor * collegeFactor);
        data.push([j, i, value]);
      }
    }
    HTChart.setOption({ series: [{ data }] });
  }

  // 更新性别比例图表
  if (GenderRatioChart) {
    const data2025 = [157, 66].map(v => Math.round(v * timeFactor * collegeFactor));
    GenderRatioChart.setOption({
      series: [{
        data: [
          { value: data2025[0], symbol: pathSymbols.man },
          { value: data2025[1], symbol: pathSymbols.woman }
        ]
      }]
    });
  }
};

// 组件挂载时初始化
onMounted(() => {
  updateDateTime();
  setInterval(updateDateTime, 1000);
  initCharts();
});

// 监听筛选器变化
watch([selectedTimeRange, selectedCollege, selectedGrade], () => {
  updateCharts();
});

// 组件卸载时销毁图表
onUnmounted(() => {
  RChart?.dispose();
  LChart?.dispose();
  GChart?.dispose();
  BChart?.dispose();
  HTChart?.dispose();
  GenderRatioChart?.dispose();
});
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
}


.filters {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  margin-top: 15px;
  background: rgba(255, 255, 255, 0.15);
  padding: 12px 20px;
  border-radius: 8px;
  width: 100%;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group p {
  margin: 0;
  color: #333;
}

.filter-group select {
  padding: 8px 15px;
  border-radius: 6px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
  margin-bottom: 30px;
}

.chart-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  height: 380px;
  display: flex;
  flex-direction: column;
}

.chart-container h2 {
  margin-bottom: 15px;
  color: #2c3e50;
  font-size: 1.2rem;
}

.chart-wrapper {
  flex: 1;
  min-height: 0;
}

@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

footer {
  text-align: center;
  padding: 20px;
  color: #777;
  font-size: 0.9rem;
  border-top: 1px solid #eee;
  margin-top: 30px;
}
</style>